package com.amphiprion.prototype.component;

import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;

import com.amphiprion.prototype.ScreenProperty;

public class TextComponent extends GameComponent {
	private int color;
	private float textSize;
	private Paint paintText;
	private String[] texts;
	private float spacing;

	public TextComponent(String text, float textSize, int color, float x, float y, int alpha) {
		this(new String[] { text }, textSize, color, x, y, alpha, 0.0f);
	}

	public TextComponent(String[] texts, float textSize, int color, float x, float y, int alpha, float spacing) {
		super();
		this.texts = texts;
		this.color = color;
		this.textSize = textSize;
		this.x = x;
		this.y = y;
		this.spacing = spacing;
		this.alpha = alpha;
		paintText = new Paint();
		paintText.setColor(color);
		paintText.setTextSize(textSize);
		paintText.setFakeBoldText(true);
		paintText.setAntiAlias(true);
	}

	@Override
	public void onDraw(Canvas canvas, ScreenProperty screenProperty) {
		if (alpha == 0) {
			return;
		}
		if (texts.length > 1) {
			float startY = y;
			float heightText = paintText.getTextSize() + spacing / 2;
			if (texts.length % 2 == 0) {
				startY -= heightText * (texts.length - 2) / 2 - heightText / 2;
			} else {
				startY -= heightText * (texts.length - 1) / 2;
			}
			for (int i = 0; i < texts.length; i++) {
				drawText(canvas, texts[i], x, startY, scale, screenProperty);
				startY += heightText;
			}
		} else {
			drawText(canvas, texts[0], x, y, scale, screenProperty);
		}

	}

	private void drawText(Canvas canvas, String str, float centerX, float centerY, float scale, ScreenProperty screenProperty) {

		paintText.setAlpha(alpha);
		float pSize = paintText.getTextSize();
		// if ("center".equals(alignment)) {
		centerX -= scale * paintText.measureText(str) / 2;
		// }
		paintText.setTextSize(pSize * screenProperty.screenScale * scale);
		Matrix m = new Matrix();
		// m.postTranslate(-canvas.getWidth() / 2, -canvas.getHeight() / 2);
		m.postRotate(screenProperty.screenRotation);
		if (screenProperty.screenRotation == 0) {
			// m.postTranslate(canvas.getWidth() / 2, canvas.getHeight() / 2);
		} else {
			m.postTranslate(canvas.getWidth(), 0);
		}
		float txtX;
		float txtY;
		txtX = centerX * screenProperty.screenScale;
		txtY = centerY * screenProperty.screenScale;
		txtY += pSize * 0.3 * screenProperty.screenScale * scale;

		canvas.save();
		canvas.setMatrix(m);
		canvas.drawText(str, txtX - screenProperty.screenOffsetX, txtY - screenProperty.screenOffsetY, paintText);
		// canvas.drawRect(0, 0, 400, 240, paint);
		canvas.restore();
		paintText.setTextSize(pSize);

	}

	@Override
	public void activate() {
		// Nothing to do
	}

	@Override
	public void desactivate() {
		// Nothing to do
	}

	public void setText(String string) {
		texts[0] = string;

	}

}
